import axios from 'axios';
import { getToken } from './cookies';
const BASE_API_URL = 'https://dbyxs.top';

interface RequestOptions<T = any> {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: T;
  header?: Record<string, string>;
  timeout?: number;
}

interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
  success: boolean;
}

// 创建 axios 实例
const service = axios.create({
  baseURL: BASE_API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 修改请求函数
export const request = async <R = any, T = any>(
  options: RequestOptions<T>
): Promise<ResponseData<R>> => {
  try {
    const { url, method = 'GET', data, header } = options;
    const token = getToken(); // 从本地存储获取 token
    console.log('token', token);
    // 合并请求头，优先使用传入的 header
    const mergedHeaders = {
      ...(token ? { Authorization: `Bearer ${token}` } : {}), // 自动携带 token
      ...header,
    };
    const response = await service.request({
      url,
      method,
      // GET 请求使用 params，其他方法用 data
      params: method === 'GET' ? data : undefined,
      data: method !== 'GET' ? data : undefined,
      headers: mergedHeaders,
    });

    const result: ResponseData<R> = response.data;

    // 检查业务状态码（假设成功状态为 success === true）
    if (!result.success) {
      throw new Error(result.message || '请求失败');
    }

    return result; // 显式返回结果
  } catch (error: any) {
    console.error('请求错误:', error);

    // 修改 Toast 调用方式为网页可用
    if (typeof document !== 'undefined') {
      alert(error.message || '网络连接异常');
    }

    // 抛出自定义错误对象，包含更多信息
    const errorMessage = error.response?.data?.message || error.message || '未知错误';
    throw new Error(errorMessage);
  }
};

// 示例用法：
// GET请求
// request<string>({ url: '/api/test', method: 'GET' });

// POST请求
// request<{ id: number }, { name: string }>({
//   url: '/api/create',
//   method: 'POST',
//   data: { name: 'test' },
// });